package com.jzo2o.market.handler;

import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

import static com.jzo2o.market.constants.RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME;
import static com.jzo2o.redis.constants.RedisSyncQueueConstants.*;

/**
 * 营销系统定时任务
 *
 * @author zhy
 */
@Component
@Slf4j
public class XxlJobHandler {

	@Resource
	private IActivityService activityService;
	@Resource
	private ICouponService couponService;
	@Resource
	private SyncManager syncManager;

	@Resource(name = "syncDataToCouponThreadPool")
	private ThreadPoolExecutor threadPoolExecutor;

	/**
	 * 活动状态修改，
	 * 1.活动进行中状态修改
	 * 2.活动已失效状态修改
	 * 每分钟执行一次
	 */
	@XxlJob("updateActivityStatus")
	public void updateActivityStatus() {
		log.info("定时修改活动状态...");
		try {
			activityService.updateStatus();
		} catch (Exception e) {
			log.error("定时修改活动状态失败", e);
			throw new ForbiddenOperationException("定时修改活动状态失败");
		}
	}

	/**
	 * 已领取优惠券自动过期任务
	 * 每小时执行一次
	 */
	@XxlJob("processExpireCoupon")
	public void processExpireCoupon() {
		log.info("已领取优惠券自动过期任务...");
		try {
			couponService.processExpireCoupon();
		} catch (Exception e) {
			log.error("已领取优惠券自动过期任务失败", e);
			throw new ForbiddenOperationException("已领取优惠券自动过期任务失败");
		}
	}

	/**
	 * 活动预热
	 *
	 * @return:
	 * @param:
	 */
	@XxlJob("activityPreheat")
	public void activityPreheat() {
		log.info("活动预热...");
		try {
			activityService.preHeat();
		} catch (Exception e) {
			log.error("活动预热失败", e);
			throw new ForbiddenOperationException("活动预热失败");
		}
	}

	/**
	 * 抢券结果同步任务
	 *
	 * @return:
	 * @param:
	 */
	@XxlJob("seizeCouponSyncJob")
	public void seizeCouponSyncJob() {
		log.info("抢券结果同步任务...");

		// 调用数据同步方法，将 Redis 中的数据同步到 MySQL
		syncManager.start(COUPON_SEIZE_SYNC_QUEUE_NAME, MODE_SINGLE, MODE_SINGLE, threadPoolExecutor);
	}

}
